<template>
  <div 
  class="vk-switch" 
  :class="{ 
  'is-disabled': disabled,
  ['vk-switch--${size}']:size,
  'is-checked' :checked
  }" @click="switchValue">
  
    <input
      ref="inputRef"
      type="checkbox"
      class="vk-switch__input"
      :checked="checked"
      :disabled="disabled"
      role="switch"
      :name="name"
      :id="id"
      @keydown.enter="switchValue"
    ></input>
    <div class="vk-switch__core">
        <div class="vk-switch__core-inner">
            <span class="vk-switch__core-inner-text" v-if="checked">{{activeText}}</span>
            <span class="vk-switch__core-inner-text" v-else>{{inactiveText}}</span>
        </div>
        <div class="vk-switch__core-action"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  defineProps,
  defineEmits,
  defineOptions,
  withDefaults,
  ref,
  computed,onMounted,watch
} from "vue";
import { SwitchProps, SwitchEmits } from "./types";

defineOptions({
  name: "VkSwitch",
  inheritAttrs: false, // 是否继承属性
});

const props = withDefaults(defineProps<SwitchProps>(), {
    activeValue:true,
    inactiveValue:false,
});
const emits = defineEmits<SwitchEmits>();

const innerValue = ref(props.modelValue);
const inputRef=ref<HTMLInputElement>()

// 现在是否被选中
const checked = computed(() => innerValue.value===props.activeValue);
const switchValue=()=>{
    if(props.disabled)return 
    const newValue=checked.value?props.inactiveValue:props.activeValue
    innerValue.value=newValue
    emits('update:modelValue',newValue)
    emits('change',newValue)
}

onMounted(()=>{
    inputRef.value!.checked=checked.value
})

watch(checked,(newValue)=>{
    inputRef.value!.checked=newValue
}
)
watch(()=>props.modelValue,(newValue)=>{
    innerValue.value=newValue
})

</script>

<style scoped></style>
